package com.xukehong.demo.util.send;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.xukehong.demo.constant.Constants;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @author xkh
 * 2020/8/20
 */
public class QiNiuYunUtil {


    /**
     * 简单上传凭证
     */
    public static String SimpleUploadAuth() {
        Auth auth = Auth.create(Constants.QNY_ACCESS_KEY, Constants.QNY_SECRET_KEY);
        String upToken = auth.uploadToken(Constants.QNY_BUCKET_NAME);
        return upToken;
    }


    /**
     * 简单文件上传
     */
    public static String SimpleUpload(MultipartFile file) {
        Configuration cfg = new Configuration(Zone.zone2());
        cfg.useHttpsDomains = false;
        UploadManager uploadManager = new UploadManager(cfg);
        String upToken = SimpleUploadAuth();
        Response response = null;
        String suffixName = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffixName;
        try {

            response = uploadManager.put(file.getBytes(), fileName, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Constants.QNY_OUTER_CHAIN_URL+fileName;
    }

}
